package me.jiatao.viewmodel

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.activity.viewModels
import androidx.lifecycle.SavedStateViewModelFactory
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import me.jiatao.viewmodel.custom.ArgViewModel
import me.jiatao.viewmodel.custom.ArgViewModelFactory
import me.jiatao.viewmodel.model.CommViewModel
import me.jiatao.viewmodel.model.SavedStateViewModel

class MainActivity : AppCompatActivity(){

    /**
     * viewModels<T>()需要导入包
     * implementation 'androidx.activity:activity-ktx:1.2.3'
     */
    private val myViewModel by viewModels<CommViewModel>()
    private var commValue = 0

    /**
     * 使用工厂创建ViewModel
     */
    private val argViewModel by lazy {
        ViewModelProvider(this, ArgViewModelFactory("hello"))
            .get(ArgViewModel::class.java)
    }

    /**
     * 延迟创建ViewModel
     */
    private val mySavedStateViewModel by lazy {
        ViewModelProvider(this, SavedStateViewModelFactory(application, this))
            .get(SavedStateViewModel::class.java)
    }


    lateinit var commText: TextView
    lateinit var viewModelText: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        commText = findViewById(R.id.comm_text)
        viewModelText = findViewById(R.id.view_model_text)

        /**
         * 屏幕旋转当前值会重置成 0
         */
        commText.text = commValue.toString()
        /**
         * 屏幕旋转当前值不变
         */
        viewModelText.text = argViewModel.numberString.toString()


    }

    fun changeValue(view: View) {
        commValue++
        commText.text = commValue.toString()

        argViewModel.numberString++
        viewModelText.text = argViewModel.numberString.toString()
    }

    fun goToSecond(view: View) {
        startActivity(Intent(this, SecondActivity::class.java))
    }
}